class MyBlockingQueue{
    private int[] data = new int[100];
    private volatile int usedSize = 0 ;
    private volatile int head = 0 ;
    private volatile int tail = 0 ;

    public synchronized void put(int elem) throws InterruptedException {
         while (usedSize == data.length){
             this.wait();
         }
         data[tail] = elem ;
         tail ++ ;
         usedSize ++ ;
         if(tail == data.length){
             tail = 0 ;
         }
         this.notify();
    }
    public synchronized int take() throws InterruptedException {
        while (usedSize == 0){
            this.wait();
        }
        int ret = data[head];
        head ++ ;
        usedSize -- ;
        if(head == data.length){
            head = 0 ;
        }
         this.notify();
        return ret ;
    }
}



public class Test2 {

    public static void main(String[] args) {
       MyBlockingQueue myBlockingQueue = new MyBlockingQueue();
       Thread t1 = new Thread(()->{
           int num = 1 ;
           while(true){
                try {
                    Thread.sleep(500);

                    myBlockingQueue.put(num);
                    System.out.println("生成者生产:" + num);
                    num ++ ;
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }
       });
       Thread t2 = new Thread(()->{
           while(true){
               try {
                   int ret = myBlockingQueue.take();
                   System.out.println("消费者消费:"+ret);
               } catch (InterruptedException e) {
                   throw new RuntimeException(e);
               }
           }
       });
        t1.start();
        t2.start();



    }
}
